
Date.prototype.format = function(fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份   
        "d+": this.getDate(), //日   
        "h+": this.getHours(), //小时   
        "m+": this.getMinutes(), //分   
        "s+": this.getSeconds(), //秒   
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
        "S": this.getMilliseconds()             //毫秒   
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt; 
}

//时间格式转换为时间戳
function js_strto_time(time) {
    var new_str = time.replace(/:/g, '-');
    new_str = new_str.replace(/ /g, '-');
    new_str = new_str.replace(/\//g, '-');
    var arr = new_str.split("-");
    var datum = new Date(Date.UTC(arr[0], arr[1] - 1, arr[2], arr[3] - 8, arr[4], arr[5]));
    return strtotime = datum.getTime() / 1000;
}
//转换为正常时间格式
function tr_time(str) {
    str = str.split(" ");
    var yymmdd = str[0];
    var hh = str[1].split(":")[0];
    var mi = str[1].split(":")[1];
    var astr = str[2];
    if (astr == "PM") {
        hh = 12 + parseInt(hh);
    }
    return yymmdd + " " + hh + ":" + mi + ":00";
}
//时间戳数据转换为时间格式
function js_date_time(unixtime) {
    var timestr = new Date(parseInt(unixtime) * 1000);
    var datetime = timestr.toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
    if (datetime.indexOf("上午") != -1) {
        datetime = datetime.replace(/上午/g, "");
        datetime = datetime.split(":")[0] + ":" + datetime.split(":")[1];
        datetime = datetime + " AM"
    }
    if (datetime.indexOf("下午") != -1) {
        datetime = datetime.replace(/下午/g, "");
        datetime = datetime.split(":")[0] + ":" + datetime.split(":")[1];
        datetime = datetime + " PM"
    }
    return datetime;
}

//获取url参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
        return unescape(r[2]);
    return null;
}

//返回上一级
function previous() {
    window.location = "../policyList.html?type=" + type + "&id=" + DepotID + "&name=" + base64.encode(DepotName) + "";
}

var base64 = new Base64();
var type = getQueryString("type");
var DepotID = getQueryString("DepotID");
var DepotName = getQueryString("DepotName");
DepotName = base64.decode(DepotName);

var PolicyObj = {
    "AppType": "",
    "AppID": "",
    "AppName": "",
    "U_Signatures": {
        "U_Signature": []
    },
    "MessageSerialNo": "123"
}

function generateParameter() {
    var obj = {
        AppType: $(".AppType").val(),
        AppID: $(".AppID").val(),
        AppName: $(".AppName").val(),
        U_Signatures: PolicyObj.U_Signatures,
        MessageSerialNo: PolicyObj.MessageSerialNo
    }
    return obj;
}

function save() {
    var form = $(".main-container .form-horizontal").validate();
    if (!form.form()) {
        return;
    }
    
    var comment = $(".policy_desc").val();
    var policy = generateParameter();
    if (policy.AppID === "0" && policy.AppName === "") {
        alert("请输入应用名称！");
        return;
    }
    
    policy = JSON.stringify(policy);
        
        $.ajax({
            type: "POST",
            async: false,
            url: "../../action/policy/create.do",
            data: {comment: comment, policy: policy, type: type, instance: DepotName},
            dataType: "json",
            success: function (data) {
                if (data.result == "true") {
                    alert("添加成功！");
                    previous();
                } else {
                    alert("添加失败!")
                }
            }
        });
}

function edit(){
    var form = $(".main-container .form-horizontal").validate();
    if (!form.form()) {
        return;
    }
    
    var comment = $(".policy_desc").val();
    var policy = generateParameter();
    if (policy.AppID === "0" && policy.AppName === "") {
        alert("请输入应用名称！");
        return;
    }
    
    policy = JSON.stringify(policy);
        
        $.ajax({
            type: "POST",
            async: false,
            url: "../../action/policy/update.do",
            data: {messageNo: id, comment: comment, policy: policy, type: type, instance: DepotName},
            dataType: "json",
            success: function (data) {
                if (data.result == "true") {
                    alert("修改成功！");
                    previous();
                } else {
                    alert("修改失败!")
                }
            }
        });
}

function showData(resp) {
    var messageType = resp.MessageType;
    var messageNo = resp.MessageNo;
    var instanceName = resp.Instance;
    var comment = resp.Comment;
    PolicyObj = resp.Content;
    
    $(".policy_desc").val(comment);
    $(".AppType").val(PolicyObj.AppType);
    $(".AppID").val(PolicyObj.AppID);
    $(".AppName").val(PolicyObj.AppName);
    
    refreshAppFuther();
}

function refreshAppFuther() {
    var obj = $(".AppFuther tbody");
    var cont = "";
    var number = 0;
    var webTypes = PolicyObj.U_Signatures.U_Signature;
    for (var i in webTypes) {
        cont += "<tr>";
        cont += "<td>" + (webTypes[i].U_Protocol == "6" ? "TCP" : "UDP") + "</td>";
        cont += "<td>" + webTypes[i].U_SourceIP.IPv4Address + "</td>";
        cont += "<td>" + webTypes[i].U_SourcePort + "</td>";
        cont += "<td>" + webTypes[i].U_DestIP.IPv4Address + "</td>";
        cont += "<td>" + webTypes[i].U_DestPort + "</td>";
        cont += "<td><a href='javascript:viewKeyWord("+ number +")'>查看关键字</a> <a href='javascript:delAppFuther(" + number + ")'>&nbsp;删&nbsp;除&nbsp;</a></td>";
        cont += "</tr>";
        number++;
    }
    obj.html("");
    obj.append(cont);
}

function delAppFuther(index) {
    PolicyObj.U_Signatures.U_Signature.splice(index, 1);
    refreshAppFuther();
}

var KeyWords = []
function viewKeyWord(index) {
    KeyWords = PolicyObj.U_Signatures.U_Signature[index].U_KWs.U_KW;
    $("#offset").val("");
    $("#keyword").val("");
    refreshKeyWord();
    $("#KeyWordModal").modal('show');
}

function addKeyWord() {
    var form = $("#KeyWordModal .form-horizontal").validate();
    if (!form.form()) {
        return;
    }
    
    KeyWords.push({
        U_OffsetBase: $("#offsetBase").val(),
        U_Offset: $("#offset").val(),
        U_KWValue: $("#keyword").val()
    });
    refreshKeyWord();
    
    $("#offset").val("");
    $("#keyword").val("");
}

function refreshKeyWord() {
    var obj = $(".KeyWordTable tbody");
    var number = 0, cont = '';
    for (var i in KeyWords) {
        cont  += "<tr>";
        cont += "<td>" + (KeyWords[i].U_OffsetBase === "0" ?  "从TCP/UDP载荷头起算" : "从TCP/UDP载荷尾倒算") +"</td>";
        cont += "<td>" + KeyWords[i].U_Offset + "</td>";
        cont += "<td>" + KeyWords[i].U_KWValue + "</td>";
        cont += "<td><a href='javascript:removeKeyWord(" + number + ")'>&nbsp;移&nbsp;除&nbsp;</a></td>"
        cont += "</tr>"
        number++;
    }
    obj.html(cont);
}

function removeKeyWord(index) {
    KeyWords.splice(index, 1);
    refreshKeyWord();
}

function addCustomFutherBox(){
    var cont = '';
    cont += "<div class='modal fade' id='myModal' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>";
    cont += "            <div class='modal-dialog'>";
    cont += "                <div class='modal-content'>";
    cont += "                    <div class='modal-header'>";
    cont += "                        <button type='button' class='close' data-dismiss='modal'><span aria-hidden='true'>&times;</span></button>";
    cont += "                        <h4 class='modal-title' id='myModalLabel'>添加自定义特征</h4>";
    cont += "                    </div>";
    cont += "                    <div class='modal-body'>";
    cont += "                        <form class='form-horizontal'>";
    cont += "                            <div class=' row-fluid'>";
    cont += "                                <div class='control-group'>";
    cont += "                                    <label class='control-label' for='AppProtocal'>应用协议：</label>";
    cont += "                                    <div class='controls'>";
    cont += "                                        <select id='AppProtocal' name='AppProtocal' class='AppProtocal' required>";
    cont += "                                            <option value='6'>TCP</option>";
    cont += "                                            <option value='17'>UDP</option>";
    cont += "                                        </select>";
    cont += "                                    </div>";
    cont += "                                </div>";
    cont += "                                <div class='control-group'>";
    cont += "                                    <label class='control-label' for='SrcIPType'>源IP类型：</label>";
    cont += "                                    <div class='controls'>";
    cont += "                                        <select id='SrcIPType' name='SrcIPType' class='SrcIPType' required>";
    cont += "                                            <option value='IPv4'>IPv4</option>";
    cont += "                                            <option value='IPv6'>IPv6</option>";
    cont += "                                        </select>";
    cont += "                                    </div>";
    cont += "                                </div>";
    cont += "                                <div class='control-group'>";
    cont += "                                    <label class='control-label' for='SrcIP'>源IP：</label>";
    cont += "                                    <div class='controls'>";
    cont += "                                        <input type='text' id='SrcIP' name='SrcIP' class='SrcIP' required />";
    cont += "                                    </div>";
    cont += "                                </div>";
    cont += "                                <div class='control-group'>";
    cont += "                                    <label class='control-label' for='SrcPort'>源端口：</label>";
    cont += "                                    <div class='controls'>";
    cont += "                                        <input type='text' id='SrcPort' name='SrcPort' class='SrcPort number' required />";
    cont += "                                    </div>";
    cont += "                                </div>";
    cont += "                                <div class='control-group'>";
    cont += "                                    <label class='control-label' for='DstIPType'>目的IP类型：</label>";
    cont += "                                    <div class='controls'>";
    cont += "                                        <select id='DstIPType' name='DstIPType' class='DstIPType' required>";
    cont += "                                            <option value='IPv4'>IPv4</option>";
    cont += "                                            <option value='IPv6'>IPv6</option>";
    cont += "                                        </select>";
    cont += "                                    </div>";
    cont += "                                </div>";
    cont += "                                <div class='control-group'>";
    cont += "                                    <label class='control-label' for='DstIP'>目的IP：</label>";
    cont += "                                    <div class='controls'>";
    cont += "                                        <input type='text' id='DstIP' name='DstIP' class='DstIP' required />";
    cont += "                                    </div>";
    cont += "                                </div>";
    cont += "                                <div class='control-group'>";
    cont += "                                    <label class='control-label' for='DstPort'>目的端口：</label>";
    cont += "                                    <div class='controls'>";
    cont += "                                        <input type='text' id='DstPort' name='DstPort' class='DstPort number' required />";
    cont += "                                    </div>";
    cont += "                                </div>";
    cont += "                            </div>";
    cont += "                        </form>";
    cont += "                    </div>";
    cont += "                    <div class='modal-footer'>";
    cont += "                        <a href='javascript:void(0)' class='btn btn-default' onclick='closeBox()'>取消</a>";
    cont += "                        <a href='javascript:void(0)' class='btn btn-primary' onclick='addAppFuther()'>确定</a>";
    cont += "                    </div>";
    cont += "                </div>";
    cont += "            </div>";
    cont += "        </div>";
    $("body").append(cont);
    $("#myModal").modal("show");
}

function closeBox() {
    $("#myModal").modal('hide');
    $("#myModal").remove();
}

function closeKeyWordBox() {
    $("#KeyWordModal").modal('hide');
}

function addAppFuther() {
    var form = $("#myModal .form-horizontal").validate();
    if (!form.form()) {
        return;
    }
    
    var obj = {
        "U_Protocol": $("#AppProtocal").val(),
        "U_SourceIP": {
            "IPType": $("#SrcIPType").val(),
            "IPv4Address": $("#SrcIP").val()
        }, 
        "U_SourcePort": $("#SrcPort").val(),
        "U_DestIP": {
            "IPType": $("#DstIPType").val(),
            "IPv4Address": $("#DstIP").val()
        },
        "U_DestPort": $("#DstPort").val(),
        "U_KWs": {
            "U_KW":[]
        }
    }
    
    PolicyObj.U_Signatures.U_Signature.push(obj);
    refreshAppFuther();
    closeBox();
}
/*
 * 查看旧版本的策略内容
 */
function show_oldPolicy(array, number) {
    var souData = array[number];
    $(".header").text("当前策略在" + souData.CreateTime + "创建,ID为" + souData.MessageNo + ",版本号为" + souData.MessageSerialNo + ",属于" + souData.Instance + "策略库");
    
    showData(souData);
}

/*
 *获取所有版本的策略内容 
 */
function getAllPolicy() {
    $.ajax({
        type: "GET",
        async: false,
        url: "../../action/policy/history_policy_info.do",
        data: {type: type, instance: getQueryString("DepotName"), messageNo: id},
        dataType: "json",
        success: function(data) {
            policyArray = data;
            policyAmount = data.length
        }
    });
}